<template>
  <a-spin :spinning="confirmLoading">
    <!-- tab分栏 -->
    <table-sort class="custom-table-sort" ref="tableSort" :sortList="sortList" @changeTab="changeTab"></table-sort>
    <!-- 内容 -->
    <div class="table-sort-content-parent">
      <div class="table-sort-content" @wheel="handleWheel">
        <a-card :bordered="false" id="table-sort-1">
          <!-- 基本信息 -->
          <sku-basic-information ref="SkuBasicInformation" :model="model" :originModel="originModel" />
        </a-card>
        <a-card :bordered="false" style="margin-top: 16px;" id="table-sort-2">
          <!-- 供应商信息 -->
          <sku-supplier ref="SkuSupplierRef" :model="model" />
        </a-card>
        <a-card :bordered="false" style="margin-top: 16px;" id="table-sort-3" v-if="model.productType != '1'">
          <!-- SKU -->
          <sku ref="SkuRef" :model="model" :originModel="originModel" />
        </a-card>
        <a-card :bordered="false" style="margin-top: 16px;" id="table-sort-4">
          <!-- 报关信息 -->
          <sku-declare ref="SkuDeclareRef" :model="model" />
        </a-card>
        <a-card :bordered="false" style="margin-top: 16px;" id="table-sort-5">
          <!-- 描述 -->
          <sku-describe ref="SkuDescribeRef" :model="model" />
        </a-card>
        <a-card :bordered="false" style="margin-top: 16px;" id="table-sort-6">
          <!-- 测量尺码 -->
          <sku-measure-size :model="model" @handleGenerate="handleGenerate" />
        </a-card>
        <!-- 尺码表 -->
        <a-card :bordered="false" style="margin-top: 16px;" id="table-sort-7">
          <sku-size-chart ref="SkuSizeChartRef" :model="model" :generateResult="generateResult" />
        </a-card>
        <!-- 产品图片 -->
        <a-card :bordered="false" style="margin-top: 16px;" id="table-sort-8">
          <sku-product-img ref="skuProductImgRef" :model="model" :originModel="originModel" />
        </a-card>
      </div>
    </div>
  </a-spin>
</template>

<script>
  import { httpAction, getAction, putAction } from '@/api/manage'
  import TableSort from '@/components/table/TableSort'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import SkuBasicInformation from './SkuSubmodule/SkuBasicInformation'
  import SkuSupplier from './SkuSubmodule/SkuSupplier'
  import Sku from './SkuSubmodule/Sku'
  import SkuDeclare from './SkuSubmodule/SkuDeclare'
  import SkuDescribe from './SkuSubmodule/SkuDescribe'
  import SkuMeasureSize from './SkuSubmodule/SkuMeasureSize'
  import SkuSizeChart from './SkuSubmodule/SkuSizeChart'
  import SkuProductImg from './SkuSubmodule/SkuProductImg'
  export default {
    name: 'ProductLibrarySkuForm',
    mixins:[JeecgListMixin],
    components: {
      TableSort,
      SkuBasicInformation,
      SkuSupplier,
      Sku,
      SkuDeclare,
      SkuDescribe,
      SkuMeasureSize,
      SkuSizeChart,
      SkuProductImg
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        model:{
          tagList: '',
          supplier: {},
          customs: {},
          description: {},
          skuList: [],
          imageList: []
        },
        originModel: {},
        generateResult: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 8 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules: {},
        url: {
          add: "/hzkj-product/product/productLibrary/sku/add",
          edit: "/hzkj-product/product/productLibrary/sku/edit",
          queryById: "/hzkj-product/product/productLibrary/sku/queryById",
          processChange: "/hzkj-product/product/productLibrary/sku/processChange"
        },
        sortList: [
          {
            text: '基本信息',
            value: '1',
          },
          {
            text: '供应商信息',
            value: '2',
          },
          {
            text: 'SKU',
            value: '3',
          },
          {
            text: '报关信息',
            value: '4',
          },
          {
            text: '描述',
            value: '5',
          },
          {
            text: '测量尺码',
            value: '6',
          },
          {
            text: '尺码表',
            value: '7',
          },
          {
            text: '产品图片',
            value: '8',
          }
        ],
        tabSort: '1',
        disableMixinCreated: true,
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      }
    },
    watch: {
      'model.productType': {
        handler(val){
          // 单属性无sku
          let flag = this.sortList.some(item => item.text === 'SKU');
          if(this.model.productType === '1' && flag){
            this.sortList.splice(2, 1);
          }else if(this.model.productType === '2' && !flag){
            this.sortList.splice(2, 0, {
              text: 'SKU',
              value: '3',
            });
          }
        }
      }
    },
    created () {
      //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
      add () {
        this.edit(this.modelDefault);
      },
      edit (record) {    
        this.model = Object.assign(this.model, record);
        this.originModel = Object.assign(this.model, record);
        this.model.tagList = (this.model.tagList && this.model.tagList.map(item => item.id) || []).join(',') || '';
        this.handleModel();
        this.visible = true;
        if(this.model.id){
          this.queryById();
        }
      },
      async handleValid(){
        let tabList = document.querySelectorAll('.custom-table-sort .ant-tabs-nav .ant-tabs-tab');
        let information = await this.$refs.SkuBasicInformation.getInformationList();
        if(!information){
          tabList[0].classList.add('show-dot');
          return false;
        }else{
          tabList[0].classList.remove('show-dot');
        }

        let supplier = await this.$refs.SkuSupplierRef.getSupplierList();
        if(!supplier){
          tabList[1].classList.add('show-dot');
          return false;
        }else{
          tabList[1].classList.remove('show-dot');
        }

        if(this.$refs.SkuRef){
          let skuList = await this.$refs.SkuRef.getSkuList();
          if(!skuList){
            tabList[2].classList.add('show-dot');
            return false;
          }else{
            tabList[2].classList.remove('show-dot');
          }
        }

        let customsList = await this.$refs.SkuDeclareRef.getCustomsList();
        let validIndex = 3;
        if(this.model.productType === '1'){
          validIndex = 2;
        }
        if(!customsList){
          tabList[validIndex].classList.add('show-dot');
          return false;
        }else{
          tabList[validIndex].classList.remove('show-dot');
        }

        let descriptionList = await this.$refs.SkuDescribeRef.getDescriptionList();
        let validIndex1 = 4;
        if(this.model.productType === '1'){
          validIndex1 = 3;
        }
        if(!descriptionList){
          tabList[validIndex1].classList.add('show-dot');
          return false;
        }else{
          tabList[validIndex1].classList.remove('show-dot');
        }

        let imageList = await this.$refs.skuProductImgRef.getValidImageList();
        let validIndex2 = 7;
        if(this.model.productType === '1'){
          validIndex2 = 6;
        }
        if(!imageList){
          tabList[validIndex2].classList.add('show-dot');
          return false;
        }else{
          tabList[validIndex2].classList.remove('show-dot');
        }

        await this.$refs.SkuSizeChartRef.getSizeTable();

        return true;
      },
      submitForm (type) {
        return new Promise(async (resolve, reject) => {
          const that = this;
          let httpurl = '';
          let method = '';
          let params = Object.assign({}, this.model);
          if(!this.model.id){
            httpurl+=this.url.add;
            method = 'post';
          }else{
            httpurl+=this.url.edit;
            method = 'post';

            // 校验各个子模块
            const flag = await this.handleValid();
            if(!flag) return;
            // 单属性，清空
            if(this.model.productType === '1'){
              params.skuList = [];
            }else{
              params.skuList = this.model.skuList;
            }
            params.imageList = this.$refs.skuProductImgRef.getImageList();
            params.tagList = this.$refs.SkuBasicInformation.getTagList();
            params.sizeTable = this.model.sizeTable;
          }
          delete params.sizeSchemeList;
          delete params.sizeTableSchemeList;
          that.confirmLoading = true;
          httpAction(httpurl,params,method).then((res)=>{
            if(res.success){
              that.$message.success(res.message);
              // 提交审批不用刷新列表
              if(!type){
                that.$emit('ok');
              }
              resolve();
            }else{
              that.$message.warning(res.message);
            }
          }).finally(() => {
            that.confirmLoading = false;
          })
        })
      },
      changeTab(value){
        this.tabSort = value;
        document.getElementById(`table-sort-${value}`).scrollIntoView({ behavior: 'smooth' });
      },
      handleWheel(e){
        let domList = document.querySelectorAll('.table-sort-content .ant-card');
        domList.forEach(dom => {
          if(dom.getBoundingClientRect().top < 300){
            this.tabSort = dom.getAttribute('id').split('-').pop();
            this.$refs.tableSort.defaultActiveKey = this.tabSort;
          }
        })
      },
      handleGenerate(generateResult){
        this.generateResult = generateResult;
      },
      queryById(){
        getAction(this.url.queryById, { id: this.model.id }).then((res) => {
          if(res.success){
            let model = res.result || {};
            this.model = {...this.model, ...model};
            this.model.tagList = (this.model.tagList && this.model.tagList.map(item => item.id) || []).join(',') || '';
            this.handleModel();
          }else{
            this.$message.warning(res.message);
          }
        })
      },
      handleModel(){
        this.model.productType = this.model.productType === '0' ? '' : this.model.productType;
        this.model.supplier = this.model.supplier ? this.model.supplier : {};
        this.model.customs = this.model.customs ? this.model.customs : {};
        this.model.description = this.model.description ? this.model.description : {};
        this.model.skuList = this.model.skuList ? this.model.skuList : [];
        this.model.imageList = this.model.imageList ? this.model.imageList : [];

        this.generateResult = this.model.sizeTable ? {
          ...this.model.sizeTable,
          tableHeader: JSON.parse(this.model.sizeTable.tableHeader),
          tableData: JSON.parse(this.model.sizeTable.tableData),
        } : {}
      },
      handleProcessChange(productStatus){
        this.submitForm(1).then(() => {
          let params = {
            skuIdsList: [this.model.id],
            productStatus
          }
          putAction(this.url.processChange, params).then((res) => {
            if(res.success){
              this.$message.success(res.message);
              this.$emit('ok');
            }else{
              this.$message.warning(res.message);
            }
          })
        })
      }
    }
  }
</script>

<style lang="less" scoped>
/deep/.ant-form-item{
  display: flex;
  flex-direction: column;
  .ant-form-item-label{
    text-align: left;
  }
}
.custom-table-sort /deep/.ant-tabs-nav .ant-tabs-tab{
  position: relative;
  &::after{
    content: '';
    width: 6px;
    height: 6px;
    border-radius: 50%;
    background-color: red;
    display: block;
    position: absolute;
    top: 12px;
    right: 12px;
    display: none;
  }
}
.custom-table-sort /deep/.ant-tabs-nav .ant-tabs-tab.show-dot{
  &::after{
    display: block;
  }
}
/deep/.sku-title{
  font-size: 15px;
  font-weight: 700;
  border-bottom: 3px solid #f5f5f5;
  width: calc(100% + 24px * 2);
  margin: -10px 0 0 -24px;
  padding: 0 0 10px 24px;
}
</style>